﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using CVsharp.Models.DAL.Account;
using CVsharp.Models.DAL.Account.Interface;
using CVsharp.Models.Entities;
using CVsharp.MVClib.ICO.Unity;
using CVsharp.WebLib.Cache;
using Microsoft.Practices.Unity;

namespace CVsharp.MVClib.Authorize
{
    public class CurrentUserAccount
    {
        //菜单
        public IList<Guid> MenuPermission { get; set; }
        //功能权限
        public IList<sysActionPermission> ActionPermission { get; set; }
        /// <summary>
        /// 缓存当前用户的权限与菜单
        /// </summary>
        public CurrentUserAccount()
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                throw new Exception("用户未登录"); //必须要用户Form验证后才能使用CurrentUser
            //TODO 修改为使用Unity获取类型
            var webbMemory = new WebMemory();
            if (webbMemory.GetSessionCache("currentuserAccount") == null)
            {
                var actionPermission = ContainerFactory.GetContainer().Resolve<IsysActionPermission>();
                ActionPermission = actionPermission.GetByRoids(Roles.GetRolesForUser(Membership.GetUser().UserName));//获取该用户所属角色全部可服务列表
                var sysMenuNode = new SysMenuNode();
                MenuPermission = sysMenuNode.GetByUser((Guid)Membership.GetUser().ProviderUserKey);
                webbMemory.SetSessionCache("currentuserAccount", this);
            }
            else
            {
                var u = (CurrentUserAccount)webbMemory.GetSessionCache("currentuserAccount");
                MenuPermission = u.MenuPermission;
                ActionPermission = u.ActionPermission;
            }
        }
    }
}
